<template>
    <van-index-bar :index-list="indexList">
        <template v-for="item in datalist" :key="item.type">
            <van-index-anchor :index="item.type" />
            <van-cell v-for="city in item.list" :key="city.cityId" :title="city.name" @click="handleChange(city)" />
        </template>
    </van-index-bar>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRouter } from "vue-router";
import axios from 'axios';
import _ from 'lodash';
import { IndexBar as vanIndexBar, IndexAnchor as vanIndexAnchor, Cell as vanCell } from 'vant';
import useCityStore from '../store/cityStore.js'

const datalist = ref([])
const store = useCityStore()
const router = useRouter()

onMounted(async () => {
    const res = await axios({
        url: 'https://m.maizuo.com/gateway?k=7351131',
        headers: {
            'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"16927511235634589070458881"}',
            'X-Host': 'mall.film-ticket.city.list'
        },
    })
    datalist.value = filterCities(res.data.data.cities)
})

const indexList = computed(() => datalist.value.map(item => item.type))

const handleChange = ({ name, cityId }) => {
    //更新选择的城市
    store.changeCity(name, cityId)

    //返回上一级页面
    router.go(-1)
}


//方法一
// const filterCities = (cities) => {
//     //构造key
//     const letterArr = []
//     for (let i = 65; i < 91; i++) {
//         letterArr.push(String.fromCharCode(i))
//     }
//     console.log(letterArr);

//     //构造value
//     let newCities = []
//     for (let i = 0; i < letterArr.length; i++) {
//         newCities.push({
//             type: letterArr[i],
//             list: cities.filter(city => city.pinyin.substring(0, 1).toUpperCase() === letterArr[i])
//         })
//     }

//     //去除长度为0的list，filter返回的是一个新的数组，需要覆盖更新原数组
//     newCities = newCities.filter(item => item.list.length)
//     console.log(newCities);
// }

//方法二:使用lodash库函数
const filterCities = (cities) => {
    //先排序，不然key会乱序
    cities.sort((item1, item2) => item1.pinyin.substring(0, 1).toUpperCase().charCodeAt() - item2.pinyin.substring(0, 1).toUpperCase().charCodeAt())

    const groupObj = _.groupBy(cities, item => item.pinyin.substring(0, 1).toUpperCase())


    const newCities = []
    for (let i in groupObj) {
        newCities.push({
            type: i,
            list: groupObj[i]
        })
    }
    console.log(newCities);
    return newCities
}
</script>